﻿using System;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;

namespace Medianamik.UI.Controls
{
    public class CodePostalTextBox : BaseMedianamikControl
    {
        protected const string PostalCodeRegex = @"^((\d{5}-\d{4})|(\d{5})|([A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d))$";

        private readonly TextBox _txtFirstPart = new TextBox
        {
            ID = ControlToValidateId,
            MaxLength = 3,
            CssClass = "TxtBox",
            Width=Unit.Pixel(30)
        };
        private readonly TextBox _txtSecondPart = new TextBox
        {
            ID = ControlToValidateId + "_2",
            MaxLength = 3,
            CssClass = "TxtBox",
            Width = Unit.Pixel(30)
        };
        private readonly CustomValidator _cvPostalCode = new CustomValidator
        {
            ID = ControlToValidateId + "_validator"
        };

        public BasePage BasePage
        {
            get { return (BasePage) base.Page; }
        }

        public override object GetValue()
        {
            return string.Format("{0} {1}",
                _txtFirstPart.Text,
                _txtSecondPart.Text).Trim().ToUpper();
        }

        public override void SetValue(object value)
        {
            _txtFirstPart.Text = string.Empty;
            _txtSecondPart.Text = string.Empty;

            if (value != null)
            {
                var postalCode = value.ToString().Replace(" ", string.Empty);
                if (postalCode.Length == 6)
                {
                    _txtFirstPart.Text = postalCode.Substring(0, 3);
                    _txtSecondPart.Text = postalCode.Substring(3, 3);
                }
            }
        }

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            Controls.Add(_txtFirstPart);
            Controls.Add(_txtSecondPart);
            Controls.Add(_cvPostalCode);

            _cvPostalCode.ServerValidate += cvPostalCode_ServerValidate;
            _cvPostalCode.ValidationGroup = DefaultValidationGroupName;
            _cvPostalCode.ErrorMessage = string.Format("{0} {1}", Label, REGEX);
            _cvPostalCode.Display = ValidatorDisplay.None;

            if (pUseDataSource)
                SetValue(DataSource);
        }

        protected void cvPostalCode_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = !IsRequired || Regex.Match(GetValue().ToString(), PostalCodeRegex).Success;
        }

        public override Type TypeOfValue
        {
            get { return typeof(string); }
        }
    }
}
